/**

 @Name：layuiAdmin iframe版核心模块
 @Author：贤心
 @Site：http://www.layui.com/admin/
 @License：LPPL
    
 */

layui.define('view', function (exports) {
	var $ = layui.jquery,
		laytpl = layui.laytpl,
		element = layui.element,
		setter = layui.setter,
		view = layui.view,
		// device = layui.device(),
		$win = $(window),
		$body = $('body'),
		container = $('#' + setter.container),
		SHOW = 'layui-show',
		HIDE = 'layui-hide',
		THIS = 'layui-this',
		DISABLED = 'layui-disabled',
		// TEMP = 'template',
		APP_BODY = '#LAY_app_body',
		APP_FLEXIBLE = 'LAY_app_flexible',
		FILTER_TAB_TBAS = 'layadmin-layout-tabs',
		APP_SPREAD_SM = 'layadmin-side-spread-sm',
		TABS_BODY = 'layadmin-tabsbody-item',
		ICON_SHRINK = 'layui-icon-shrink-right',
		ICON_SPREAD = 'layui-icon-spread-left',
		SIDE_SHRINK = 'layadmin-side-shrink',
        SIDE_MENU = 'LAY-system-side-menu',
        prexshow =  false,

		//通用方法
		admin = {
			v: '1.0.0-beta8 std',
			//数据的异步请求
			req: view.req,
			// 主题数据
			zltheme: null,
			// 所有主题数据
			allThemeData: null,
			//发送验证码
			sendAuthCode: function (options) {
				options = $.extend({
					seconds: 60,
					elemPhone: '#LAY_phone',
					elemVercode: '#LAY_vercode'
				}, options);

				var seconds = options.seconds,
					btn = $(options.elem),
					// token = null,
					timer, countDown = function (loop) {
						seconds--;
						if (seconds < 0) {
							btn.removeClass(DISABLED).html('获取验证码');
							seconds = options.seconds;
							clearInterval(timer);
						} else {
							btn.addClass(DISABLED).html(seconds + '秒后重获');
						}

						if (!loop) {
							timer = setInterval(function () {
								countDown(true);
							}, 1000);
						}
					};

				options.elemPhone = $(options.elemPhone);
				options.elemVercode = $(options.elemVercode);

				btn.on('click', function () {
					var elemPhone = options.elemPhone,
						value = elemPhone.val();

					if (seconds !== options.seconds || $(this).hasClass(DISABLED)) return;

					if (!/^1\d{10}$/.test(value)) {
						elemPhone.focus();
						return layer.msg('请输入正确的手机号')
					}

					if (typeof options.ajax === 'object') {
						var success = options.ajax.success;
						delete options.ajax.success;
					}

					admin.req($.extend(true, {
						url: '/auth/code',
						type: 'get',
						data: {
							phone: value
						},
						success: function (res) {
							layer.msg('验证码已发送至你的手机，请注意查收', {
								icon: 1,
								shade: 0
							});
							options.elemVercode.focus();
							countDown();
							success && success(res);
						}
					}, options.ajax));
				});
			},

			//屏幕类型
			screen: function () {
				var width = $win.width()
				if (width >= 1200) {
					return 3; //大屏幕
				} else if (width >= 992) {
					return 2; //中屏幕
				} else if (width >= 768) {
					return 1; //小屏幕
				} else {
					return 0; //超小屏幕
				}
			},

			//清除本地 token，并跳转到登入页
			exit: view.exit,

			//侧边伸缩
			sideFlexible: function (status) {
				var app = container,
					iconElem = $('#' + APP_FLEXIBLE),
					screen = admin.screen();

				//设置状态，PC：默认展开、移动：默认收缩
				if (status === 'spread') {
					//切换到展开状态的 icon，箭头：←
					iconElem.removeClass(ICON_SPREAD).addClass(ICON_SHRINK);

					//移动：从左到右位移；PC：清除多余选择器恢复默认
					if (screen < 2) {
						app.addClass(APP_SPREAD_SM);
					} else {
						app.removeClass(APP_SPREAD_SM);
					}

					app.removeClass(SIDE_SHRINK)
				} else {
					//切换到搜索状态的 icon，箭头：→
					iconElem.removeClass(ICON_SHRINK).addClass(ICON_SPREAD);

					//移动：清除多余选择器恢复默认；PC：从右往左收缩
					if (screen < 2) {
						app.removeClass(SIDE_SHRINK);
					} else {
						app.addClass(SIDE_SHRINK);
					}

					app.removeClass(APP_SPREAD_SM)
				}

				layui.event.call(this, setter.MOD_NAME, 'side({*})', {
					status: status
				});
			},

			//xss 转义
			escape: function (html) {
				return String(html || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
					.replace(/</g, '&lt;').replace(/>/g, '&gt;')
					.replace(/'/g, '&#39;').replace(/"/g, '&quot;');
			},

			//事件监听
			on: function (events, callback) {
				return layui.onevent.call(this, setter.MOD_NAME, events, callback);
			},
			//弹出面板

			popup: view.popup,
			//右侧面板
			popupRight: function (options) {
				//layer.close(admin.popup.index);
				return admin.popup.index = layer.open($.extend({
					type: 1,
					id: 'LAY_adminPopupR',
					anim: -1,
					title: false,
					closeBtn: false,
					offset: 'r',
					shade: 0.1,
					shadeClose: true,
					skin: 'layui-anim layui-anim-rl layui-layer-adminRight',
					area: '300px'
				}, options));
			},
			defaulTheme: [{
				'theme_title': "黑色主题", // 主题名称
				'theme_title-py': 'HeiSeZhuTi',
				// logo
				'logoFontColorInput': 'rgba(255,255,255,.8)', // logo字体颜色
				'logoBgInput': '#20222A', // logo背景颜色
				// 导航栏
				'navFont': "Microsoft YaHei", // 导航栏字体
				'navBgInput': "#FFFFFF", // 导航栏背景
				'navFontColorInput': "#333333", // 导航栏 字体颜色
				'navIconColorInput': "#333333", // 导航栏 图标颜色
				// 左侧菜单
				'searchBoxBgInput': '#374850', // 搜索框背景
				'searchBoxFontColorInput': '#FFFFFF', // 搜索框字体色
				'menuBgInput': "#20222A", // 左侧菜单背景
				'childMenuBgInput': 'rgba(0, 0, 0, .3)',
				'menuFont': "Microsoft YaHei", // 左侧菜单字体
				'menuFontColorInput': "#FFFFFF", // 左侧菜单字体颜色
				'menuSelectedBgInput': '#277FD0', // 左侧菜单 选中项背景颜色
				'menuSelectedFontColorInput': '#FFFFFF', // 左侧菜单 选中项字体颜色
				'menuItemBorderColorInput': '无', // 左侧菜单 选中项字体颜色
				// 标准按钮
				'btnBgInput': "#277FD0", // 标准按钮背景
				'btnFont': "Microsoft YaHei", // 标准按钮字体
				'btnFontColorInput': "#FFFFFF", // 标准按钮字体颜色
				'btnIconColorInput': "#FFFFFF", // 标准按钮图标颜色
				// 警告按钮
				'dangerBtnBgInput': '#FF5722', // 警告按钮背景
				'dangerBtnFont': 'Microsoft YaHei', // 警告按钮字体
				'dangerBtnFontColorInput': "#FFFFFF", // 警告按钮字体颜色
				'dangerBtnIconColorInput': "#FFFFFF", // 警告按钮图标颜色
				// 开关按钮
				'switchBgInput': "#5FB878", // 开关按钮背景
				'switchFont': "Microsoft YaHei", // 开关按钮字体
				'switchFontColorInput': "#FFFFFF", // 开关按钮字体颜色
				// 复选框-默认
				'checkBoxBgInput': "#5FB878", // 复选框-默认 背景
				'checkBoxFontColorInput': "#FFFFFF", // 复选框-默认 字体颜色
				'checkboxFont': "Microsoft YaHei", // 复选框-默认 字体
				// 复选框-原始
				'originCheckBoxBgInput': "#5FB878", // 复选框-原始 背景
				// 'originCheckBoxFont': "", // 复选框-原始 字体
				'originCheckBoxFontColorInput': "#FFFFFF", // 复选框-原始 字体颜色
				// 单选框
				'radioBgInput': "#5FB878", // 单选框背景
				// 'radioFont': "", // 单选框字体
				// 'radioFontColorInput': "#fff", // 单选框字体颜色
				// 窗口
				'layerTitleBgInput': "#F8F8F8", // 窗口标题背景
				'layerCloseBtnColor': "1", // 窗口关闭按钮颜色
				'layerTitleFontColorInput': "#333333", // 窗口标题字体颜色

				'id': '25CE6A8B1C',
				// 'isActive': true, // 是否为选中主题
			}],
			//主题设置
			theme: function (options) {
				if (options && options.childMenuBgInput && options.childMenuBgInput.indexOf('.') != -1 && options.childMenuBgInput.indexOf(',') != -1) {
					var arr =options.childMenuBgInput.split(',');
					arr.pop();
					options.childMenuTipsBgInput = arr.join()+')';
				}
				options.layerMinBtnColor = options.layerCloseBtnColor == 1 ? "#2E2D3C" : "#fff";
				options.layerMaxBtnColor = options.layerCloseBtnColor == 1 ? "-32" : "-102";
				options.layerMaxMinBtnColor = options.layerCloseBtnColor == 1 ? "-65" : "-120";
				options.menuItemBorderColorInput = options.menuItemBorderColorInput == '无' ? 'none' : ('1px solid ' + options.menuItemBorderColorInput);
				var cid = 'ZL_layadmin_theme',
					id = 'ZL_layadmin_theme_p',
					style = document.createElement('style'),
					styleElem = document.getElementById(id),

					// iframe 子页面主题调整
					childStyleText = laytpl([
						//主题色
						'.layui-layer .layui-layer-title,' // 弹层标题背景颜色 待定
						,'.layui-layer-iframe .layui-layer-title'
						, '{background-color:{{d.layerTitleBgInput}} !important;color:{{d.layerTitleFontColorInput}};}' //
						, '.layui-layer-setwin .layui-layer-min cite' //
                        , '{background-color:{{d.layerMinBtnColor}};}' // 
						, '.layui-layer-setwin .layui-layer-max' //
						, '{background-position:{{d.layerMaxBtnColor}}px -40px;}' //
						, '.layui-layer-setwin .layui-layer-max.layui-layer-maxmin' //
						, '{background-position:{{d.layerMaxMinBtnColor}}px -40px;}'
						, '.layui-layer-setwin .layui-layer-close1' //
						, '{background-position:{{d.layerCloseBtnColor}}px -40px;}' //
						, '.layui-btn' // 标准按钮 背景颜色 字体颜色 字体
						, '{background-color:{{d.btnBgInput}};color:{{d.btnFontColorInput}};font-family:{{d.btnFont}} !important;}'// 
						, '.layui-btn i' //
						, '{color:{{d.btnIconColorInput}} !important;}' //
						, '.layui-btn.layui-btn-danger' // 警告按钮 背景颜色 字体颜色 字体
						, '{background-color:{{d.dangerBtnBgInput}};color:{{d.dangerBtnFontColorInput}};font-family:{{d.dangerBtnFont}} !important;}' //
						, '.layui-btn.layui-btn-danger i' //
						, '{color:{{d.dangerBtnIconColorInput}} !important;}' //
						, '.layui-form-switch.layui-form-onswitch' // 开关按钮 背景颜色 字体颜色 字体
						, '{border-color:{{d.switchBgInput}};background-color:{{d.switchBgInput}};}' //
						, '.layui-form-switch.layui-form-onswitch em' //
						, '{color:{{d.switchFontColorInput}} !important;}' //
						, '.layui-unselect.layui-form-switch em' //
						, '{font-family:{{d.switchFont}} !important;}' //
						, '.layui-form-switch.layui-form-onswitch i' //
						, '{background-color:{{d.switchFontColorInput}};}' //
						, '.layui-form-checkbox.layui-form-checked' // 复选框-默认 背景颜色 字体颜色 字体
						, '{border-color:{{d.checkBoxBgInput}};}' //
						, '.layui-unselect.layui-form-checkbox' //
						, '{font-family:{{d.checkboxFont}} !important;}' //
						, '.layui-form-checkbox.layui-form-checked span' //
						, '{background-color:{{d.checkBoxBgInput}};color:{{d.checkBoxFontColorInput}};}' //
						, '.layui-form-checkbox.layui-form-checked i' //
						, '{color:{{d.checkBoxBgInput}};}' //
						, '.layui-form-checkbox.layui-form-checked[lay-skin="primary"] i' // 复选框-原始 背景颜色 字体颜色
						, '{border-color:{{d.originCheckBoxBgInput}};background-color:{{d.originCheckBoxBgInput}};color:{{d.originCheckBoxFontColorInput}};}' //
						, '.layui-form-checkbox.layui-form-checked[lay-skin="primary"] span' //
						, '{color: #666;background: none!important;}' //
						, '.layui-form-radio.layui-form-radioed i' //
						, '{color:{{d.radioBgInput}};}' //
						, '.layui-form-select dl dd.layui-this'
						, '{background-color:{{d.menuBgInput}};}'
						, '.layui-tab-brief>.layui-tab-title .layui-this:after, .layui-tab-brief>.layui-tab-more li.layui-this:after'
						, '{border-color:{{d.menuBgInput}};}'
					].join('')).render(options),
					// iframe 父页面主题调整
					styleText = laytpl([
						//主题色
						'.layui-side-menu' // 左侧菜单树背景色
						, '{font-family:{{d.menuFont}} !important;background-color:{{d.menuBgInput}};}' //
						, '.navbar-side-search' //
						, '{background-color:{{d.menuBgInput}};}' //
						, '.navbar-side-search input' //
						, '{background-color:{{d.searchBoxBgInput}};border-color:{{d.searchBoxBgInput}};color:{{d.searchBoxFontColorInput}};}' //
						, '.navbar-side-search input:hover' //
						, '{border-color:{{d.searchBoxBgInput}};}' //
						, '.navbar-side-search input:focus' //
						, '{border-color:{{d.searchBoxBgInput}};}' //
						, '.navbar-side-search input::-webkit-input-placeholder' //
						, '{color:{{d.searchBoxFontColorInput}};}' //
						, '.navbar-side-search input::-moz-placeholder' //
						, '{color:{{d.searchBoxFontColorInput}};}' //
						, '.navbar-side-search input::-ms-input-placeholder' //
						, '{color:{{d.searchBoxFontColorInput}};}' //
						, '.layui-side-menu .layui-nav.layui-nav-tree a,' // 左侧菜单树字体色和图标颜色
						, '.layui-side-menu .layui-nav.layui-nav-tree i.layui-icon' //
						, '{color:{{d.menuFontColorInput}} !important;}' //
						, '.layui-side-menu .layui-nav.layui-nav-tree' //
						, '{border-top:{{d.menuItemBorderColorInput}};}' //
                        , '.layui-side-menu .layui-nav.layui-nav-tree li.layui-nav-item' //
                        , '{border-bottom:{{d.menuItemBorderColorInput}};}' //
						, '.layui-side-menu .layui-nav.layui-nav-tree span.layui-nav-more' // 三角图标颜色
						, '{border-top-color:{{d.menuFontColorInput}} !important;}' //
						, '.layui-side-menu .layui-nav.layui-nav-tree .layui-nav-itemed>a span.layui-nav-more' //
						, '{border-top-color:{{d.menuBgInput}} !important;}' //
                        , '.layui-side-menu .layui-nav.layui-nav-tree .layui-nav-itemed>.layui-nav-child' //
                        , '{background-color:{{d.childMenuBgInput}} !important;}' //
						, '.layui-side-menu .layui-nav.layui-nav-tree .layui-this a,' // 左侧菜单树选中项背景色和字色
						, '.layui-side-menu .layui-nav.layui-nav-tree .layui-nav-bar' //
						, '{background-color:{{d.menuSelectedBgInput}} !important;color:{{d.menuSelectedFontColorInput}} !important;}' //
						, '.layui-layout-admin .layui-header' // 顶部导航栏背景色和字体
						, '{font-family:{{d.navFont}} !important;background-color:{{d.navBgInput}};}' //
						, '.layui-layout-admin .layui-header a:hover,' //
						, '.layui-layout-admin .layui-header a cite' // 顶部导航栏字色
						, '{color:{{d.navFontColorInput}};}' //
						, '.layui-layout-admin .layui-header a i.layui-icon,' //
						, '.layui-layout-admin .layui-header a i.zlui-icon,' //
						, '.layui-layout-admin .layui-header a i.fa' // 顶部导航栏图标颜色
						, '{color:{{d.navIconColorInput}};}' //
						, '.layui-layout-admin .layui-header a span.layui-nav-more' // 顶部导航栏三角图标颜色
						, '{border-top-color:{{d.navIconColorInput}} !important;}' //
						, '.layui-layout-admin .layui-header .layui-nav .layui-nav-mored' // 顶部导航栏三角图标hover时颜色
						, '{border-top-color:{{d.navBgInput}} !important;border-bottom-color:{{d.navIconColorInput}} !important;}' //
						, '.layui-layout-admin .layui-logo' // 左上角logo 背景色和字色
						, '{background-color:{{d.logoBgInput}};color:{{d.logoFontColorInput}};}' //
						, '.layadmin-pagetabs .layui-tab-title li:after,' //
						, '.layadmin-pagetabs .layui-tab-title li.layui-this:after' // pagetabs页签 顶部边框色
						, '{background-color:{{d.menuBgInput}};}' //
						, '.layui-tab-brief>.layui-tab-title .layui-this:after, .layui-tab-brief>.layui-tab-more li.layui-this:after'
						, '{border-color:{{d.menuBgInput}};}'
                        , '.layui-layer-tips.menuTips .layui-layer-content' //
                        , '{background-color:{{d.childMenuTipsBgInput}};color:{{d.menuFontColorInput}};}' //
                        , '.layui-layer-tips.menuTips .layui-layer-content i' //
                        , '{border-bottom-color:{{d.childMenuTipsBgInput}};}' //
					].join('')).render(options);

				if ('styleSheet' in style) {
					style.setAttribute('type', 'text/css');
					style.styleSheet.cssText = styleText;
				} else {
					style.innerHTML = styleText;
				}
				style.id = id;

				styleElem && $('body')[0].removeChild(styleElem);
				$('body')[0].appendChild(style);
				$('body').attr('layadmin-themealias', options["theme_title-py"]);

				var iframeBody = $(".layadmin-iframe").contents();
				// frameTheme(iframeBody)


				function frameTheme(iframeBody){
					for (var i = 0; i < iframeBody.length; i++) {
						var c_style = $(iframeBody[i])[0].createElement('style'),
							c_styleElem = $(iframeBody[i])[0].getElementById(cid);
						if ('styleSheet' in c_style) {
							c_style.setAttribute('type', 'text/css');
							c_style.styleSheet.cssText = childStyleText;
						} else {
							c_style.innerHTML = childStyleText;
						}
						c_style.id = cid;

						c_styleElem && $(iframeBody[i]).find("body")[0].removeChild(c_styleElem);
						$(iframeBody[i]).find("body")[0] && $(iframeBody[i]).find("body")[0].appendChild(c_style);
						$(iframeBody[i]).find("body").attr('layadmin-themealias', options["theme_title-py"]);

						if($(iframeBody[i]).find("body")[0] && $(iframeBody[i]).find("body").find("iframe").contents().length > 0){
							frameTheme($(iframeBody[i]).find("body").find("iframe").contents())
						}
					}
				}

				setTimeout(function(){
					$('body').addClass('loaded');
					$('#loader-wrapper .load_title').remove();
					frameTheme(iframeBody)
				},50);
			},

			//记录最近一次点击的页面标签数据
			tabsPage: {},

			//获取页面标签主体元素
			tabsBody: function (index) {
				return $(APP_BODY).find('.' + TABS_BODY).eq(index || 0);
			},

			//切换页面标签主体
			tabsBodyChange: function (index, options) {
				options = options || {};

				admin.tabsBody(index).addClass(SHOW).siblings().removeClass(SHOW);
				events.rollPage('auto', index);

				//执行 {setter.MOD_NAME}.tabsPage 下的事件
				layui.event.call(this, setter.MOD_NAME, 'tabsPage({*})', {
					url: options.url,
					text: options.text
				});
			},

			//resize事件管理
			resize: function (fn) {
				var router = layui.router(),
					key = router.path.join('-');
				$win.off('resize', admin.resizeFn[key]);
				fn(), admin.resizeFn[key] = fn;
				$win.on('resize', admin.resizeFn[key]);
			},
			resizeFn: {},
			runResize: function () {
				var router = layui.router(),
					key = router.path.join('-');
				admin.resizeFn[key] && admin.resizeFn[key]();
			},
			delResize: function () {
				var router = layui.router(),
					key = router.path.join('-');
				$win.off('resize', admin.resizeFn[key])
				delete admin.resizeFn[key];
			},

			//关闭当前 pageTabs
			closeThisTabs: function () {
				if (!admin.tabsPage.index) return;
				$(TABS_HEADER).eq(admin.tabsPage.index).find('.layui-tab-close').trigger('click');
			},

			//全屏
			fullScreen: function () {
				var ele = document.documentElement,
					reqFullScreen = ele.requestFullScreen || ele.webkitRequestFullScreen ||
					ele.mozRequestFullScreen || ele.msRequestFullscreen;
				if (typeof reqFullScreen !== 'undefined' && reqFullScreen) {
					reqFullScreen.call(ele);
				}
			},

			//退出全屏
			exitScreen: function () {
				// var ele = document.documentElement
				if (document.exitFullscreen) {
					document.exitFullscreen();
				} else if (document.mozCancelFullScreen) {
					document.mozCancelFullScreen();
				} else if (document.webkitCancelFullScreen) {
					document.webkitCancelFullScreen();
				} else if (document.msExitFullscreen) {
					document.msExitFullscreen();
				}
			}
			//……
		};

	//事件
	var events = admin.events = {
		//伸缩
		flexible: function (othis) {
			var iconElem = othis.find('#' + APP_FLEXIBLE),
				isSpread = iconElem.hasClass(ICON_SPREAD);
			admin.sideFlexible(isSpread ? 'spread' : null);
		},
		//刷新
		refresh: function () {
			$('.layadmin-tabsbody-shade').show();
			var iframe = admin.tabsBody(admin.tabsPage.index).find('.layadmin-iframe');
			iframe[0].contentWindow.location.reload(true);
			setTimeout(function () {
				if (admin.zltheme) {
					admin.theme(admin.zltheme)
				}
			}, 50);
			setTimeout(function () {
				$('.layadmin-tabsbody-shade').hide();
			}, 1000)
		},

		//点击消息
		message: function (othis) {
			othis.find('.layui-badge-dot').remove();
		},

		//弹出主题面板
		theme: function () {
			admin.popupRight({
				id: 'LAY_adminPopupTheme',
				content: '<div class="layui-card-header">主题管理</div>' +
					'<div class="layui-card-body layadmin-setTheme">' +
					'   <ul class="layadmin-setTheme-color"></ul>' +
					'</div>',
				success: function () {
					// view(this.id).render('system/theme')

					// 前台所有主题展示
					var param = {},
						userData = null;

					$.ajax({
						url: layui.cache['contentPath'] + '/admin/coreuser/querycuruserinfo',
						type: "POST",
						async: false,
						data: {},
						dataType: "json",
						contentType: "application/json",
						success: function (data) {
							if (data.state == 'OK') {
								userData = data.obj;
							}
						}
					});

					param.orgid = userData.currentOrgId;
					param.optid = 'DF64BCDD33324F3DA4A63973E2462391';

					$.ajax({
						url: layui.cache['contentPath'] + '/manager/coresysopt/queryxtypec',
						type: "GET",
						async: false,
						data: param,
						dataType: "json",
						contentType: "application/json",
						success: function (data) {
							var allThemeData = '',
								themeStr = '';
							if (data.state == 'OK') {
								allThemeData = eval('(' + data.obj + ')');

							}else{
								allThemeData = admin.defaulTheme;
							}

							admin.allThemeData = allThemeData;
							for (var i = 0; i < allThemeData.length; i++) {
								var item = allThemeData[i],
									flag = '';
								if (admin.zltheme) {
									if (admin.zltheme.id === item.id) {
										flag = 'layui-this';
									}
								} else {
									if (item.id === '25CE6A8B1C') {
										flag = 'layui-this';
									}
								}

								themeStr += '<li layadmin-event="setTheme" data-tid="' + item.id + '" data-alias="' + item['theme_title-py'] + '" class="' + flag + '" title="' + item.theme_title + '">' +
									'  <div class="layadmin-setTheme-title">' + item.theme_title + '</div>' +
									'  <div class="layadmin-setTheme-header" style="background-color: ' + item.navBgInput + ';"></div>' +
									'  <div class="layadmin-setTheme-side" style="background-color: ' + item.menuBgInput + ';">' +
									'    <div class="layadmin-setTheme-logo" style="background-color: ' + item.logoBgInput + ';"></div>' +
									'  </div>' +
									'</li>'
							}
							$('#LAY_adminPopupTheme').find('ul.layadmin-setTheme-color').html(themeStr);
						}
					});
				}
			});
		},

		//便签
		note: function (othis) {
			var mobile = admin.screen() < 2,
				note = layui.data(setter.tableName).note;

			events.note.index = admin.popup({
				title: '便签',
				shade: 0,
				offset: [
					'41px', (mobile ? null : (othis.offset().left - 250) + 'px')
				],
				anim: -1,
				id: 'LAY_adminNote',
				skin: 'layadmin-note layui-anim layui-anim-upbit',
				content: '<textarea placeholder="内容"></textarea>',
				resize: false,
				success: function (layero, index) {
					var textarea = layero.find('textarea'),
						value = note === undefined ? '便签中的内容会存储在本地，这样即便你关掉了浏览器，在下次打开时，依然会读取到上一次的记录。是个非常小巧实用的本地备忘录' : note;

					textarea.val(value).focus().on('keyup', function () {
						layui.data(setter.tableName, {
							key: 'note',
							value: this.value
						});
					});
				}
			})
		},

		//全屏
		fullscreen: function (othis) {
			var SCREEN_FULL = 'layui-icon-screen-full',
				SCREEN_REST = 'layui-icon-screen-restore',
				iconElem = othis.children("i");

			if (iconElem.hasClass(SCREEN_FULL)) {
				admin.fullScreen();
				iconElem.addClass(SCREEN_REST).removeClass(SCREEN_FULL);
			} else {
				admin.exitScreen();
				iconElem.addClass(SCREEN_FULL).removeClass(SCREEN_REST);
			}
		},

		//弹出关于面板
		about: function () {
			admin.popupRight({
				id: 'LAY_adminPopupAbout',
				success: function () {
					view(this.id).render('system/about')
				}
			});
		},

		//弹出更多面板
		more: function () {
			admin.popupRight({
				id: 'LAY_adminPopupMore',
				success: function () {
					view(this.id).render('system/more')
				}
			});
		},

		//返回上一页
		back: function () {
			history.back();
		},

		//主题设置
		setTheme: function (othis) {
			if (othis.hasClass(THIS)) return;
			othis.addClass(THIS).siblings('.layui-this').removeClass(THIS);
			var allThemeData = admin.allThemeData;
			for (var i = 0; i < allThemeData.length; i++) {
				if (allThemeData[i].id === othis.attr('data-tid')) {
					var params = {};
					params.UPD_SHIYCJID = 'BDB8E796652148F49E89D53CE0473E4A';
					params.UPD_CONTENT = allThemeData[i].id;
					$.ajax({
						url: layui.cache['contentPath'] + "/admin/coreupd/modify",
						type: 'POST',
						async: false,
						data: params,
						dataType: 'json',
						success: function (result) {
							if (result.state == 'OK') {
								// sessionStorage.setItem('zltheme', JSON.stringify(allThemeData[i]));
								admin.zltheme = allThemeData[i];
								admin.theme(allThemeData[i]);
								sessionStorage.setItem('zltheme', JSON.stringify(allThemeData[i]))
							}
						}
					});
					break;
				}
			}
			// var theme = setter.theme
			// ,index = othis.data('index')
			// ,nextIndex = othis.siblings('.layui-this').data('index');

			// if(othis.hasClass(THIS)) return;

			// othis.addClass(THIS).siblings('.layui-this').removeClass(THIS);

			// if(theme.color[index]){
			//   theme.color[index].index = index
			//   admin.theme({
			//     color: theme.color[index]
			//   });
			// }
		},

		//左右滚动页面标签
		rollPage: function (type, index) {
			var tabsHeader = $('#LAY_app_tabsheader'),
				liItem = tabsHeader.children('li'),
				// scrollWidth = tabsHeader.prop('scrollWidth'),
				outerWidth = tabsHeader.outerWidth(),
				tabsLeft = parseFloat(tabsHeader.css('left'));

			//右左往右
			if (type === 'left') {
				if (!tabsLeft && tabsLeft <= 0) return;

				//当前的left减去可视宽度，用于与上一轮的页标比较
				var prefLeft = -tabsLeft - outerWidth;

				liItem.each(function (index, item) {
					var li = $(item),
						left = li.position().left;

					if (left >= prefLeft) {
						tabsHeader.css('left', -left);
						return false;
					}
				});
			} else if (type === 'auto') { //自动滚动
				(function () {
					var thisLi = liItem.eq(index),
						thisLeft;

					if (!thisLi[0]) return;
					thisLeft = thisLi.position().left;

					//当目标标签在可视区域左侧时
					if (thisLeft < -tabsLeft) {
						return tabsHeader.css('left', -thisLeft);
					}

					//当目标标签在可视区域右侧时
					if (thisLeft + thisLi.outerWidth() >= outerWidth - tabsLeft) {
						var subLeft = thisLeft + thisLi.outerWidth() - (outerWidth - tabsLeft);
						liItem.each(function (i, item) {
							var li = $(item),
								left = li.position().left;

							//从当前可视区域的最左第二个节点遍历，如果减去最左节点的差 > 目标在右侧不可见的宽度，则将该节点放置可视区域最左
							if (left + tabsLeft > 0) {
								if (left - tabsLeft > subLeft) {
									tabsHeader.css('left', -left);
									return false;
								}
							}
						});
					}
				}());
			} else {
				//默认向左滚动
				liItem.each(function (i, item) {
					var li = $(item),
						left = li.position().left;

					if (left + li.outerWidth() >= outerWidth - tabsLeft) {
						tabsHeader.css('left', -left);
						return false;
					}
				});
			}
		},

		//向右滚动页面标签
		leftPage: function () {
			events.rollPage('left');
		},

		//向左滚动页面标签
		rightPage: function () {
			events.rollPage();
        },
        setPrevAndNext:function(){
            var topLayui = parent === self ? layui : window.layui;
            topLayui.index.setPrevAndNext();
            if($('.layui-icon-prev').is(':hidden')){
                events.leftPage();
            }
        },

		//关闭当前标签页
		closeThisTabs: function () {
            admin.closeThisTabs();
            events.setPrevAndNext();
		},

		//关闭其它标签页
		closeOtherTabs: function (type) {
			var TABS_REMOVE = 'LAY-system-pagetabs-remove';
			if (type === 'all') {
				$(TABS_HEADER + ':gt(0)').remove();
				$(APP_BODY).find('.' + TABS_BODY + ':gt(0)').remove();

				$(TABS_HEADER).eq(0).trigger('click');
			} else {
                var curitem;
				$(TABS_HEADER).each(function (index, item) {
					if (index && index != admin.tabsPage.index) {
						$(item).addClass(TABS_REMOVE);
						admin.tabsBody(index).addClass(TABS_REMOVE);
					}else{
                        curitem = $(item);    
                    }
				});
                $('.' + TABS_REMOVE).remove();
                if (curitem) {
                    curitem.trigger('click');
                }
				if ($('#LAY_app_tabsheader').position().left != 0) {
					$('#LAY_app_tabsheader').css('left', 0)
				}
            }
            events.setPrevAndNext();
		},

		//关闭全部标签页
		closeAllTabs: function () {
            events.closeOtherTabs('all');
			//location.hash = '';
		},

		// 刷新当前子页面
		refreshCurrentPage: function () {
			$('#LAY_app_body .layui-show iframe').attr('src', $('#LAY_app_tabsheader>li.layui-this').attr('lay-attr'));
		},

		//遮罩
		shade: function () {
			admin.sideFlexible();
		},

		//呼出IM 示例
		im: function () {
			admin.popup({
				id: 'LAY-popup-layim-demo', //定义唯一ID，防止重复弹出
				shade: 0,
				area: ['800px', '300px'],
				title: '面板外的操作示例',
				offset: 'lb',
				success: function () {
					//将 views 目录下的某视图文件内容渲染给该面板
					layui.view(this.id).render('layim/demo').then(function () {
						layui.use('im');
					});
				}
			})
		}
	};

	//初始
	! function () {
		//主题初始化
		// var local = layui.data(setter.tableName);
		// local.theme && admin.theme(local.theme);
		// // 当前设定主题设置
		if (admin.zltheme) {
			admin.theme(admin.zltheme);
		} else {
			$.ajax({
				url: layui.cache['contentPath'] + '/manager/coresysopt/querytheme',
				type: "POST",
				async: true,
				data: {},
				dataType: "json",
				contentType: "application/json",
				success: function (data) {
					if (data && data.state == 'OK' && data.obj) {
						admin.theme(eval('(' + data.obj + ')'));
						admin.zltheme = eval('(' + data.obj + ')');
						sessionStorage.setItem('zltheme', data.obj);
					}else{
						setTimeout(function(){
							$('body').addClass('loaded');
							$('#loader-wrapper .load_title').remove();
						},500);
					}
				}
			});
		}

		//常规版默认开启多标签页
		if (!('pageTabs' in layui.setter)) layui.setter.pageTabs = true

		//不开启页面标签时
		if (!setter.pageTabs) {
			$('#LAY_app_tabs').addClass(HIDE);
			container.addClass('layadmin-tabspage-none');
		}

		//低版本IE提示
		// if(device.ie && device.ie < 10){
		//   view.error('IE'+ device.ie + '下访问可能不佳，推荐使用：Chrome / Firefox / Edge 等高级浏览器', {
		//     offset: 'auto'
		//     ,id: 'LAY_errorIE'
		//   });
		// }

	}();

	//admin.prevRouter = {}; //上一个路由

	//监听 tab 组件切换，同步 index
	element.on('tab(' + FILTER_TAB_TBAS + ')', function (data) {
		admin.tabsPage.index = data.index;
	});

	//监听选项卡切换，改变菜单状态
	admin.on('tabsPage(setMenustatus)', function (router) {
		var pathURL = router.url,
			getData = function (item) {
				return {
					list: item.children('.layui-nav-child'),
					a: item.children('*[lay-href]')
				}
			},
			sideMenu = $('#' + SIDE_MENU),
			SIDE_NAV_ITEMD = 'layui-nav-itemed',

			//捕获对应菜单
			matchMenu = function (list) {
				list.each(function (index1, item1) {
					var othis1 = $(item1),
						data1 = getData(othis1),
						listChildren1 = data1.list.children('dd'),
						matched1 = pathURL === data1.a.attr('resid');

					listChildren1.each(function (index2, item2) {
						var othis2 = $(item2),
							data2 = getData(othis2),
							listChildren2 = data2.list.children('dd'),
							matched2 = pathURL === data2.a.attr('resid');

						listChildren2.each(function (index3, item3) {
							var othis3 = $(item3),
								data3 = getData(othis3),
								matched3 = pathURL === data3.a.attr('resid');

							if (matched3) {
								var selected = data3.list[0] ? SIDE_NAV_ITEMD : THIS;
								othis3.parents('dd').addClass(SIDE_NAV_ITEMD).siblings().removeClass(SIDE_NAV_ITEMD);
								othis3.parents('li.layui-nav-item').addClass(SIDE_NAV_ITEMD).siblings().removeClass(SIDE_NAV_ITEMD);
								othis3.addClass(selected).siblings().removeClass(selected); //标记选择器
								return false;
							}
						});

						if (matched2) {
							var selected = data2.list[0] ? SIDE_NAV_ITEMD : THIS;
							othis2.parents('li.layui-nav-item').addClass(SIDE_NAV_ITEMD).siblings().removeClass(SIDE_NAV_ITEMD);
							othis2.addClass(selected).siblings().removeClass(selected); //标记选择器
							return false
						}
					});

					if (matched1) {
						var selected = data1.list[0] ? SIDE_NAV_ITEMD : THIS;
						othis1.addClass(selected).siblings().removeClass(selected); //标记选择器
						return false;
					}
				});
			}

		//重置状态
		sideMenu.find('.' + THIS).removeClass(THIS);

		//移动端点击菜单时自动收缩
		if (admin.screen() < 2) admin.sideFlexible();

		//开始捕获
		matchMenu(sideMenu.children('li'));
	});

	//监听侧边导航点击事件
	element.on('nav(layadmin-system-side-menu)', function (elem) {
		if (!window.navigator.onLine && elem.attr('lay-href')) {
			// '网络未连接， 请检查网络后刷新页面'
			layer.open({
				type: 1,
				title: false,
				closeBtn: 0,
				offset: 'r',
				shade: 0,
				id: 'offline',
				area: ['calc(100% - 220px)', '100%'],
				content: '<div style="text-align: center;padding-top: 50px;">' +
					'  <i class="layui-icon layui-icon-404" style="font-size: 250px;"></i>' +
					'  <div style="font-size: 20px;">网络未连接， 请检查网络后刷新页面</div>' +
					'</div>'
			})
			return;
		}
		$('#offline').parent().remove()
		if (elem.siblings('.layui-nav-child')[0] && container.hasClass(SIDE_SHRINK)) {
			admin.sideFlexible('spread');
			layer.close(elem.data('index'));
		}
		admin.tabsPage.type = 'nav';
	});

	//监听选项卡的更多操作
	element.on('nav(layadmin-pagetabs-nav)', function (elem) {
		var dd = elem.parent();
		dd.removeClass(THIS);
		dd.parent().removeClass(SHOW);
	});

	//同步路由
	var setThisRouter = function (othis) {
			var layid = othis.attr('lay-id'),
				// attr = othis.attr('lay-attr'),
				index = othis.index();

			admin.tabsBodyChange(index, {
				url: layid
			});
			location.hash = layid === setter.entry ? '/' : '';
		},
		TABS_HEADER = '#LAY_app_tabsheader>li';

	//标签页标题点击
	$body.on('click', TABS_HEADER, function () {

        if ($('.layadmin-tabsbody-shade').length>0) {
			$('.layadmin-tabsbody-shade').hide()
        }
        
		var othis = $(this),
			index = othis.index();

		admin.tabsPage.type = 'tab';
		admin.tabsPage.index = index;

		//单页标签页
		setThisRouter(othis);
	});

	//监听 tabspage 删除
	element.on('tabDelete(' + FILTER_TAB_TBAS + ')', function (obj) {
		var othis = $(TABS_HEADER + '.layui-this');

		obj.index && admin.tabsBody(obj.index).remove();
		setThisRouter(othis);

		//移除resize事件
        admin.delResize();
        events.setPrevAndNext();
	});

	//页面跳转
	$body.on('click', '*[lay-href]', function () {
		if (!window.navigator.onLine) return;
		var othis = $(this),
			href = othis.attr('lay-href'),
			text = othis.attr('lay-text'),
			resid = othis.attr('resid'),
			// router = layui.router(),
			searchBox = othis.parents('div#admin-navbar-side').siblings('div.navbar-side-search');

		searchBox.find('ul.navbarSearchResult ').removeClass('layui-show').addClass('layui-hide');
		searchBox.find('input#navbarSearchValue').val('');
		admin.tabsPage.elem = othis;
		//admin.prevRouter[router.path[0]] = router.href; //记录上一次各菜单的路由信息

		//执行跳转
		var topLayui = parent === self ? layui : window.layui;
		topLayui.index.openTabsPage(href, text || othis.text(), resid);

		setTimeout(function () {
			if (admin.zltheme) {
				admin.theme(admin.zltheme)
			}
		}, 500)
	});

	//点击事件
	$body.on('click', '*[layadmin-event]', function () {
		var othis = $(this),
			attrEvent = othis.attr('layadmin-event');
		events[attrEvent] && events[attrEvent].call(this, othis);
	});

	//tips
	$body.on('mouseenter', '*[lay-tips]', function () {
		var othis = $(this);

		if (othis.parent().hasClass('layui-nav-item') && !container.hasClass(SIDE_SHRINK)) return;
		var tips = othis.attr('lay-tips'),
			offset = othis.attr('lay-offset'),
			direction = othis.attr('lay-direction'),
			index = layer.tips(tips, this, {
				tips: direction || 1,
				time: -1,
				// ,id: 'menuTips'
				success: function (layero, index) {
					layero.addClass('menuTips')
					if (offset) {
						layero.css('margin-left', offset + 'px');
					}
					setTimeout(function () {
						layero.show()
					}, 1000)
				}
			});
		othis.data('index', index);
	}).on('mouseleave', '*[lay-tips]', function () {
		layer.close($(this).data('index'));
	});

	//窗口resize事件
	var resizeSystem = layui.data.resizeSystem = function () {
		//layer.close(events.note.index);
		layer.closeAll('tips');

		if (!resizeSystem.lock) {
			setTimeout(function () {
				admin.sideFlexible(admin.screen() < 2 ? '' : 'spread');
				delete resizeSystem.lock;
			}, 100);
		}

		resizeSystem.lock = true;
	}
	$win.on('resize', layui.data.resizeSystem);

	//接口输出
	exports('admin', admin);
});